package com.example.demo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.util.Date;

@EnableConfigurationProperties({JWTUtils.class})
@ConfigurationProperties(prefix = "spring.jwt")
public class JWTUtils {

    public static String getHeader() {
        return header;
    }

    public static String header="LOGINTOKEN";
    private static String secret="gkk123456";
    private static String expireTime="1800000";

    /**
     * 生成token
     * @param sub 用户唯一信息
     * @return token
     */
    public  static   String createToken(String sub){
        return JWT
                .create()
                .withSubject(sub)
                .withExpiresAt(new Date(System.currentTimeMillis()+Long.parseLong(expireTime)))
                .sign(Algorithm.HMAC512(secret));
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return 用户信息
     */
    public static String validateToken(String token){
        return JWT
                .require(Algorithm.HMAC512(secret))
                .build()
                .verify(token)
                .getSubject();
    }

    /**
     * 检验Token是否需要刷新
     * @param token
     * @return
     */
    public static boolean refreshToken(String token) {
        Date expireDate = null;
        try {
            expireDate = JWT
                    .require(Algorithm.HMAC512(secret))
                    .build()
                    .verify(token)
                    .getExpiresAt();
        } catch (TokenExpiredException e) {
            return true;
        }
        return (expireDate.getTime()-System.currentTimeMillis())<0;
    }


    public String getSecret() {
        return secret;
    }
    public String getExpireTime() {
        return expireTime;
    }

}
